package com.helloDemo.Controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

	@RequestMapping("/unAuth")
	public String unAuth() {

		return "unAuth";

	}

	@RequestMapping("/demo/error")
	public String error() {

		return "error";

	}

	@RequestMapping("/toLogin")
	public String toLogin(String name, String password, Model model) {

		System.out.println("UserController.....name:" + name);

		Subject subject = SecurityUtils.getSubject();

		UsernamePasswordToken token = new UsernamePasswordToken(name, password);

		try {
			// 只要执行login方法，就会去执行userRealm中的认证逻辑
			subject.login(token);

			// 如果没有异常，代表登陆成功
			// 跳转到指定页面
			return "redirect:/index";

		} catch (UnknownAccountException u) {

			u.printStackTrace();

			// 登陆失败

			model.addAttribute("msg", "用户不存在");

			return "login";

		} catch (IncorrectCredentialsException i) {

			i.printStackTrace();

			model.addAttribute("msg", "密码错误");

			return "login";
		}

	}

	@RequestMapping("/login")
	public String login() {

		return "login";

	}

	@RequestMapping("/index")
	public String index() {

		return "index";

	}

	@RequestMapping("/add")
	public String add() {

		return "user/add";

	}

	@RequestMapping("/update")
	public String update() {

		return "user/update";

	}

	@RequestMapping("/hello")
	@ResponseBody
	public String hello() {
		System.out.println("ok");

		return "ok";
	}

	@RequestMapping("/test")
	public String test(Model model) {

		model.addAttribute("name", "刘德华");

		return "test";

	}

}
